package toubiao.service.impl;

import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.mysql.jdbc.log.Log;

import toubiao.dao.support.UserDaoI;
import toubiao.domain.po.manage.PoResource;
import toubiao.domain.po.manage.PoUser;
import toubiao.domain.vo.assist.Json;
import toubiao.domain.vo.assist.SessionInfo;
import toubiao.domain.vo.manage.Resource;
import toubiao.domain.vo.manage.User;
import toubiao.exception.CustomException;
import toubiao.service.ResourceServiceI;
import toubiao.service.UserServiceI;
import toubiao.utils.old.ProUtilPoVoConvert;
import utils.UtilString;

@Service
public class UserServiceImpl implements UserServiceI {
	private Logger logger=LoggerFactory.getLogger(UserServiceImpl.class);
	
	@Autowired
	private UserDaoI userDao;
	
	@Autowired
	private ResourceServiceI resourceService;
	
	
	    /* (非 Javadoc)
	    * 
	    * 
	    * @param user
	    * @return
	    * @throws CustomException
	    * @see toubiao.service.UserServiceI#login(toubiao.domain.vo.User)
	    */
	@Override
	public Json login(User user)  {
		Json json=new Json();
		// TODO Auto-generated method stub
		if(user==null || UtilString.isNullOrEmpty(user.getName(),user.getPwd())){
			json.setMessage("用户名 或 密码 为空.");
			return json;
		}
		
		Map<String, Object> map=new HashMap<String, Object>();
		
		map.put("name", user.getName());
		map.put("pwd", user.getPwd());
		
		String hql="select distinct u from PoUser u left join fetch u.roleSet r where u.name=:name and u.pwd=:pwd ";
		PoUser poUser=userDao.get(hql, map);
		if(poUser==null){
			json.setMessage("用户名 或 密码错误.");
			return json;
		}else{
			user=ProUtilPoVoConvert.getVo(poUser);
			SessionInfo sessionInfo=new SessionInfo();
			sessionInfo.setUserId(poUser.getId());
			sessionInfo.setUserName(poUser.getName());
			//ip 回头补充
			//获得该用户权限
			List<Resource> resourceList;
			try {
				resourceList = resourceService.getResourceListByUser(user);
			} catch (CustomException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
				json.setMessage(e.getMessage());
				return json;
			}
			Set<String> urlSet=new HashSet<>();
			for(Resource r:resourceList){
				if(r!=null && !UtilString.isNullOrEmpty(r.getUrl()))
					urlSet.add(r.getUrl());
			}
			sessionInfo.setUrlSet(urlSet);
			json.setSuccess(true);
			json.setData(sessionInfo);
			return json;
		}
		
	
	}

}
